package main

import (
	"context"
	"encoding/json"
	"fmt"
	"git.900sui.cn/kc/base/utils"
	"git.900sui.cn/kc/kcgin"
	"git.900sui.cn/kc/kcgin/logs"
	"git.900sui.cn/kc/redis"
	"git.900sui.cn/kc/rpcinterface/client/insurance"
	task "git.900sui.cn/kc/rpcinterface/client/task/insurance"
	insurance2 "git.900sui.cn/kc/rpcinterface/interface/insurance"
	"github.com/robfig/cron"
	"time"
)

/**
 * 将保险公司待上传的消费记录,进行批量加入执行消费记录交换机
 * @className insuranceConsumeLog
 * @author liyang<654516092@qq.com>
 * @date 2020/9/10 14:00
 */

const (
	insuranceConsumeLog = "insurance_task_consume_log_%s"
)

//执行任务
func execTask(){
	local,_ := time.LoadLocation("Local")
	localTime := time.Now().In(local).Unix()
	localTimeStr := time.Unix(localTime,0).Format("20060102")
	key := fmt.Sprintf("%s_%s",insuranceConsumeLog,localTimeStr)
	new(utils.KcLog).GetInstance(kcgin.AppConfig.String("crontab.log.insuranceConsumeLog"))
	var limit = 50
	var runId int
	//保险
	rpcInsurance := new(insurance.TaskPolicy).Init()
	defer rpcInsurance.Close()
	//任务
	rpcTask := new(task.InsuranceConsumeLog).Init()
	defer rpcTask.Close()
	_ = redis.RedisGlobMgr.Clear(key)
	for{
		runBytes,err  := redis.RedisGlobMgr.Get(key)
		if err != nil{
			utils.Logerr.Printf("redis err:%v",err)
			break
		}
		if runBytes == nil{
			runId = 0
		}else{
			_ = json.Unmarshal(runBytes.([]byte),&runId)
		}
		if  runId == -1{
			break
		}
		rpcInsurance := new(insurance.TaskPolicy).Init()
		defer rpcInsurance.Close()
		args := &insurance2.ArgsConsumeTask{
			RunId: runId,
			Limit: limit,
		}
		reply := []insurance2.ReplyConsumeTask{}
		if err := rpcInsurance.RunConsumeDataTask(context.Background(),args,&reply);err != nil{
			utils.Logerr.Printf("rpc request err:%v,taskId:%d",err,args.RunId)
		}
		if len(reply)<=0{
			_ = redis.RedisGlobMgr.Set(key,-1,86400)
			utils.Logerr.Printf("insurance_task_consume_log complete runId:%d",runId)
			break
		}
		var replyTask,replyUp bool
		for _,m := range reply{
			if err := rpcTask.RunInsuranceConsumeLogTask(context.Background(),&m.Id,&replyTask);err != nil{
				utils.Logerr.Printf("rpc request run err:%v,taskId:%d",err,m.Id)
			}
			if err := rpcInsurance.UpdateConsumeDataTask(context.Background(),&m.Id,&replyUp);err != nil{
				utils.Logerr.Printf("rpc request update err:%v,taskId:%d",err,m.Id)
			}
		}
		lastRunId := reply[len(reply)-1].Id
		_  = redis.RedisGlobMgr.Set(key,lastRunId,86400)
	}
	utils.Logerr.Printf("insurance_task_consume_log finish.")
}

func main() {
	logs.Info("Environment Variable:MSF_ENV:", kcgin.KcConfig.RunMode)
	c := cron.New()
	//每天凌晨三点执行
	spec := "0 0 3 * * ?" //秒-分-时-日-月-周【忽略】
	_ = c.AddFunc(spec,execTask)
	c.Start()
	select {}
}
